import { defineStore } from 'pinia';
import { transformData } from '@/utils';
import { DataNode } from '@/types/app';

export const useUserInfo = defineStore('userInfo', {
  state: () => {
    // 尝试从 localStorage 中读取 userInfo
    const storedUserInfos = localStorage.getItem('userInfo');
    const token = localStorage.getItem('token');

    return {
      token: token || null,
      userInfos: storedUserInfos
        ? JSON.parse(storedUserInfos)
        : { menus: [], perms: [] },
    };
  },
  actions: {
    async setUserInfo(name: string, token: string) {
      this.token = token;
      this.userInfos = name;
      // 将 userInfo 和 token 保存到 localStorage 根据实际情况修改
      localStorage.setItem('userInfo', JSON.stringify(this.userInfos));
      localStorage.setItem('LOGICFLOW-CHAT-TOKEN', token);
    },
    getToken() {
      if (!this.token) {
        this.token = localStorage.getItem('token');
      }
      return this.token;
    },
    getUserInfo() {
      if (!this.token) {
        this.userInfos = localStorage.getItem('userInfos');
      }
      return this.userInfos;
    },
    clearToken() {
      this.token = null;
      this.userInfos = { menus: [], perms: [] };
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
    },
  },
});
